﻿#region File Header
//-----------------------------------------------------------------------------
// Bricks' Bane
//
// Copyright (C) 2010 Julien Villers
// This program is distributed under the terms of the 
// GNU Lesser General Public License (LGPL).
// See Docs/lgpl.txt and Docs/gpl.txt
//-----------------------------------------------------------------------------
#endregion

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SibLib;
using SibLib.Entities;
using SibLib.Render;
using SibLib.Render.Primitives3D;

namespace BricksBane.Entities
{
    sealed class Bullet : GameplayObject
    {
        public Wall Wall
        {
            get;
            set;
        }

        private static GeometricPrimitive m_Primitive = null;
        private Matrix m_World;

        public Bullet() :
            base()
        {

        }

        protected override void LoadContent()
        {
            base.LoadContent();

            if (m_Primitive == null)
            {
                m_Primitive = new CylinderPrimitive(GameplayScreen.Instance.GraphicsDevice, 8.0f, 3.0f, 4);
            }
        }

        private static readonly float V_SPEED = -500.0f;

        public override void Update(float timeFactor)
        {
            float newY = m_Position.Y + (V_SPEED * timeFactor);

            foreach (Brick brick in Wall)
            {
                Rectangle brickBox = brick.GetBoundingBox();
                Vector2 collisionPoint;
                if (CollisionMath.LineLineIntersect(Position, new Vector2(m_Position.X, newY), new Vector2(brickBox.Left, brickBox.Center.Y), new Vector2(brickBox.Right, brickBox.Center.Y), out collisionPoint))
                {
                    IsActive = false;
                    brick.OnBulletHit(this);
                }
            }

            Rectangle wallRect = Wall.GetBoundingBox();
            if (newY <= wallRect.Top)
            {
                IsActive = false;
            }

            m_Position.Y = newY;

            m_World = Matrix.CreateTranslation(new Vector3(m_Position, 0.0f));
        }

        public override void Draw(float timeFactor)
        {
            SceneInfo info = GameplayScreen.Instance.SceneInfo;
            m_Primitive.Draw(m_World, info.ViewMatrix, info.ProjectionMatrix, Color.Red);
        }
    }
}
